import React,{useRef} from "react";
import { Form, Input, Button,message } from 'antd';
import api from "../../api";

import './index.css'

const Login = (props:any) => {
    const form = useRef<any>(null);
    const onFinish = (values: any) => {
        // 调用api的登录接口，传递用户名密码
        api.login({
            ...values
        }).then((res:any)=>{
            if(res.success) {
                message.success('登录成功');
                // 登录成功之后把token存在本地
                const token:string = res.data.token;
                window.localStorage.setItem('token',token);
                // 清空输入框的值
                form.current.resetFields();
                // 跳转到首页
                props.history.push('/app')
                
            } else {
                message.error(res.message);
            }
        })
    };
    return (
        <div className="login">
            <div className="form-login">
                <Form
                    name="basic"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 12 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    style={{ marginTop: 100 }}
                    ref={form}
                >
                    <Form.Item
                        label="用户名"
                        name="username"
                        rules={[{ required: true, message: '请输入用户名!' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[{ required: true, message: '请输入密码!' }]}
                    >
                        <Input.Password />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </div>

        </div>
    )
};

export default Login